package com.tg.app.activity.device;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.base.BaseActivity;
import com.tg.app.R;
import com.tg.app.adapter.SinglePlayAdapter;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.util.LogUtils;
import com.tg.app.view.grid.BasePageIndicator;
import com.tg.app.view.grid.GridPagerSnapHelper;
import com.tg.app.view.grid.GridPagerUtils;
import com.tg.app.view.grid.OnPageChangeListener;
import com.tg.app.view.grid.TwoRowDataTransform;
import com.tg.app.widget.ACLinearLayoutManager;
import com.tg.app.widget.CommItemDecoration;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceItem_;

import java.util.ArrayList;
import java.util.List;

public class MultiPlayerActivity extends BaseActivity implements View.OnClickListener {
    public static final String EXT_DEVICE_TTEMS = "ext_device_items";
    private static final String TAG = "MultiPlayerActivity";
    private List<DeviceItem> deviceItems;
    private ImageButton btnPrevious, btnNext;
    private RelativeLayout relBack;
    private int selectPage = 0;
    private   BasePageIndicator indicator;

    private PowerManager.WakeLock wakeLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_player);
        hideActionBar();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        deviceItems = getIntent().getParcelableArrayListExtra(EXT_DEVICE_TTEMS);
        initView();

        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerMgr != null) {
            int flags = PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
            wakeLock = powerMgr.newWakeLock(flags, MultiPlayerActivity.class.getName());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (wakeLock != null) {
                wakeLock.acquire(); // 获取唤醒锁
            }
        } catch (Throwable ex) {}
    }

    @Override
    protected void onPause() {
        super.onPause();

        try {
            if (wakeLock != null && wakeLock.isHeld()) {
                wakeLock.release(); // 释放唤醒锁
            }
        } catch (Throwable ignored) {}
    }

    @Override
    protected void initView() {

        btnPrevious = findViewById(R.id.btn_multi_player_previous);
        btnNext = findViewById(R.id.btn_multi_player_next);
        relBack = findViewById(R.id.rl_multi_player_toolbar);
        findViewById(R.id.btn_multi_player_back).setOnClickListener(this);
        btnPrevious.setOnClickListener(this);
        btnNext.setOnClickListener(this);
        if (deviceItems!=null&&deviceItems.size()>0){
            configRecyclerView();
        }

    }


    private void passiveDeviceFilter(){
        if (deviceItems != null && deviceItems.size() > 0){
            for (int i = deviceItems.size() - 1; i > -1; i--){
                DeviceItem deviceItem = deviceItems.get(i);
                if (DeviceHelper.isPassiveDevice(deviceItem)){
                    deviceItems.remove(i);
                }
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void configRecyclerView() {
        int  column  = 2;
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        //setLayoutManager
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2, ACLinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(gridLayoutManager);


        //attachToRecyclerView
        GridPagerSnapHelper gridPagerSnapHelper = new GridPagerSnapHelper();
        gridPagerSnapHelper.setRow(2).setColumn(column);
        gridPagerSnapHelper.attachToRecyclerView(recyclerView);

        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int itemWidth = screenWidth / column;

        passiveDeviceFilter();

        //getDataSource
        deviceItems = GridPagerUtils.transformAndFillEmptyData(
                new TwoRowDataTransform<DeviceItem>(column), deviceItems);
        if (deviceItems != null) {
            TGLog.i(TAG, "deviceItems "+deviceItems.size());
        } else {
            TGLog.i(TAG, "deviceItems NULL");
        }


        //setAdapter
        SinglePlayAdapter adapter = new SinglePlayAdapter(this, deviceItems);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(CommItemDecoration.createHorizontal(Color.WHITE, 1));
        recyclerView.addItemDecoration(CommItemDecoration.createVertical(Color.WHITE, 1));

        //indicator
        indicator = (BasePageIndicator) findViewById(R.id.rv_rvg_pager_indicator);
        indicator.setRecyclerView(recyclerView);
        //Note: pageColumn must be config
        indicator.setPageColumn(column);
        indicator.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectPage = position;
                displayViews(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        recyclerView.setOnTouchListener((v, event) -> {
            displayViews(true);
            return false;
        });

        displayViews(true);

    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private final int EVENT_SHOW = 0;
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == EVENT_SHOW) {
                displayViews(false);
            }
        }
    };


    private void displayViews(boolean show) {
        handler.removeMessages(EVENT_SHOW);
        if (show) {
            relBack.setVisibility(View.VISIBLE);
            if (selectPage == 0) {
                btnPrevious.setVisibility(View.GONE);
                btnNext.setVisibility(View.VISIBLE);
                if ( indicator.pageCount()==1){
                    btnNext.setVisibility(View.GONE);
                }
            } else if (selectPage == indicator.pageCount() - 1) {
                btnPrevious.setVisibility(View.VISIBLE);
                btnNext.setVisibility(View.GONE);
            } else {
                btnPrevious.setVisibility(View.VISIBLE);
                btnNext.setVisibility(View.VISIBLE);
            }
            handler.sendEmptyMessageDelayed(EVENT_SHOW, 5000);
        } else {
            relBack.setVisibility(View.GONE);
            btnPrevious.setVisibility(View.GONE);
            btnNext.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);

        try {
            if (wakeLock != null && wakeLock.isHeld()) {
                wakeLock.release();
            }
        } catch (Throwable ignored) {}
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_multi_player_back) {
            finish();
        } else if (id == R.id.btn_multi_player_next) {
            if (indicator != null && selectPage < indicator.pageCount() - 1) {
                indicator.setCurrentItem(selectPage + 1);
            }
        } else if (id == R.id.btn_multi_player_previous) {
            if (indicator != null && selectPage > 0) {
                indicator.setCurrentItem(selectPage - 1);
            }
        }
    }

}
